package cn.com.tianpeidong.restaurantadmin.project.admin.dishes.service.impl;

import cn.com.tianpeidong.restaurantadmin.common.exception.BusinessException;
import cn.com.tianpeidong.restaurantadmin.common.util.msg.MessageUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishes.entity.Dishes;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishes.mapper.DishesMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishes.service.IDishesService;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.entity.DishesType;
import cn.com.tianpeidong.restaurantadmin.project.admin.dishestype.mapper.DishesTypeMapper;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

import static cn.com.tianpeidong.restaurantadmin.project.admin.dishes.constant.DishesConstant.MAX_PACKAGE_SIZE;

/**
 * @author tianpeidong
 */
@Service
public class DishesServiceImpl implements IDishesService {

    @Autowired
    private DishesMapper dishesMapper;

    @Autowired
    private DishesTypeMapper dishesTypeMapper;

    @Override
    public List<Dishes> listDishes(Dishes dishes) {
        return dishesMapper.listDishes(dishes);
    }

    @Override
    public Dishes getDishesById(@NonNull Long id) {
        return dishesMapper.getById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Dishes addDishes(Dishes dishes) {
        checkBasicInfo(dishes, true);
        dishes.setScore(new BigDecimal(MAX_PACKAGE_SIZE));
        dishesMapper.insertNewDishes(dishes);

        return dishes;
    }

    private void checkBasicInfo(@NonNull Dishes dishes, boolean isInsertProcess) {

        Dishes dishesDb = dishesMapper.getDishesByName(dishes.getDishesName());
        if (isInsertProcess && dishesDb != null) {
            throw new BusinessException(MessageUtils.message("dishes.name.illegal"));
        }
        if (!isInsertProcess && dishesDb != null && !dishesDb.getId().equals(dishes.getId())) {
            throw new BusinessException(MessageUtils.message("dishes.name.illegal"));
        }
        DishesType dishesType = dishesTypeMapper.getById(dishes.getDishesTypeId());
        if (dishesType == null) {
            throw new BusinessException(MessageUtils.message("dishesType.not.exist"));
        }
    }

    @Override
    public void deleteDishes(@NonNull Long id) {
        dishesMapper.deleteDishes(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Dishes editDishes(Dishes dishes) {
        dishesMapper.updateDishes(dishes);
        return dishes;
    }
}
